#!/usr/bin/env python3
import tkinter
from tkinter import ttk

win = tkinter.Tk()
win.title("Tkinter Treeview 实例")
win.geometry("453x325")


def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]

    def MB_To_MB(Traffic): return int(Traffic.replace(' MB', '')) if 'MB' in Traffic else 0
    def GB_To_MB(Traffic): return int(Traffic.replace(' GB', '')) * 1024 if 'GB' in Traffic else MB_To_MB(Traffic)
    if 'MB' in l[0][0] or 'GB' in l[0][0]:
        l.sort(key=lambda t: GB_To_MB(t[0]), reverse=reverse)
    elif 'cm' in l[0][0]:
        l.sort(key=lambda t: int(t[0].replace(' cm', '')), reverse=reverse)
    elif '元' in l[0][0]:
        l.sort(key=lambda t: int(t[0].replace(' 元', '')), reverse=reverse)
    else:
        try:
            l.sort(key=lambda t: int(t[0]), reverse=reverse)
        except:
            l.sort(reverse=reverse)
    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)
    tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))


tree = ttk.Treeview(win, show="headings", height=15)
columns = {'ID': 50, '昵称': 100, '身高': 100, '余额': 100, '流量': 100}
tree['columns'] = list(columns)
for column in columns:
    tree.heading(column, text=column)
    tree.column(column, width=columns[column], anchor='center')
    tree.heading(column, command=lambda _col=column: treeview_sort_column(tree, _col, False))

Data = [
    [1, '张三', '184 cm', '2000 元', '500 MB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [2, '李四', '170 cm', '100 元', '10 GB'],
    [3, '王五', '175 cm', '-300 元', '-200 MB']
]

for person in Data:
    tree.insert('', person[0], text='', values=person)

tree.pack()
win.mainloop()
